package com.hmdp.utils;


import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWorker {

    private static final long BEGIN_TIMESTAMP = 1640995200L;
    private static final int COUNT_BITS = 32;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public long nextId(String keyPrefix) {
        // 1、生成时间戳
        LocalDateTime now = LocalDateTime.now();//获取当前时间
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);//获取当前秒数
        long timestamp = nowSecond - BEGIN_TIMESTAMP;
        //2.生成系列号
        //2.1 获取当前日期，精确到天
        String date = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
//        System.out.println("date = "+date);
        //2.2 自增长
        Long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);

        //3.拼接并返回
        return timestamp << COUNT_BITS | count;
    }

    public static void main(String[] args) {
        LocalDateTime time = LocalDateTime.of(2022, 1, 1, 0, 0, 0);
        long second = time.toEpochSecond(ZoneOffset.UTC);//这一行将 LocalDateTime 对象转换为自 Unix 纪元以来的秒数。
        // toEpochSecond 方法需要一个 ZoneOffset 参数，表示时区偏移量。在这里，使用 ZoneOffset.UTC 表示 UTC 时区。该方法返回从 1970 年 1 月 1 日 00:00:00 UTC 到指定时间的秒数。
        System.out.println("second = " + second);
    }
}
